// ============================================================================
//
// Copyright (C) 2006-2007 Dengues
//
// Google Group: http://groups.google.com/group/dengues
// QQ Group: 24885404
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
// ============================================================================
package org.dengues.commons.utils;

import java.util.StringTokenizer;

import org.dengues.commons.connectivity.EDatabaseType;
import org.eclipse.swt.graphics.RGB;

/**
 * Qiang.Zhang.Adolf@gmail.com class global comment. Detailled comment <br/>
 * 
 * $Id: Dengues.epf 2007-11-25 qiang.zhang $
 * 
 */
public class DenguesTextUtil {

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "removeQualifier".
     * 
     * @param version
     * @return
     */
    public static String removeQualifier(String version) {
        int dotCount = 0;
        int secDotIndex = 0;
        for (int i = 0; i < version.length(); i++) {
            char ch = version.charAt(i);
            if (ch == '.') {
                dotCount++;
                if (dotCount == 3) {
                    secDotIndex = i;
                }
            }
        }
        if (dotCount > 2 && secDotIndex > 0) {
            version = version.substring(0, secDotIndex);
        }
        return version;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getNotNullString".
     * 
     * @param s
     * @return
     */
    public static String getNotNullString(String s) {
        return s == null ? "" : s; //$NON-NLS-1$
    }

    public static final String SINGLE_QUOTE = "'"; //$NON-NLS-1$

    public static final String ANTI_QUOTE = "`"; //$NON-NLS-1$

    public static final String QUOTATION_MARK = "\""; //$NON-NLS-1$

    public static final String LBRACKET = "["; //$NON-NLS-1$

    public static final String RBRACKET = "]"; //$NON-NLS-1$

    private static final int LINE_MAX_NUM = 100;

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addQuotes".
     * 
     * @param text
     * @return
     */
    public static String addQuotes(String text) {
        return addQuotes(text, QUOTATION_MARK, true);
    }

    public static String addQuotes(String text, boolean isCheck) {
        return addQuotes(text, QUOTATION_MARK, isCheck);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addQuotes".
     * 
     * @param text
     * @param quoteStyle
     * @param isCheck
     * @return
     */
    private static String addQuotes(String text, String quoteStyle, boolean isCheck) {
        String newString;

        if (quoteStyle.equals(SINGLE_QUOTE)) {
            if (isCheck) {
                text = checkStringQuotes(text);
            }
            newString = SINGLE_QUOTE + text + SINGLE_QUOTE;
        } else {
            if (isCheck) {
                text = checkStringQuotes(text);
            }
            if (quoteStyle.equals(ANTI_QUOTE)) {
                newString = ANTI_QUOTE + text + ANTI_QUOTE;
            } else if (quoteStyle.equals(LBRACKET) || quoteStyle.equals(RBRACKET)) {
                newString = LBRACKET + text + RBRACKET;
            } else {
                newString = QUOTATION_MARK + text + QUOTATION_MARK;
            }
        }
        return newString;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addSQLQuotes".
     * 
     * @param text
     * @return
     */
    public static String addSQLQuotes(String text) {
        return addSQLQuotes(text, QUOTATION_MARK);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addSQLQuotes".
     * 
     * @param text
     * @param quoteStyle
     * @return
     */
    private static String addSQLQuotes(String text, String quoteStyle) {
        String newString;

        if (quoteStyle.equals(SINGLE_QUOTE)) {
            newString = SINGLE_QUOTE + checkStringQuotes(text) + SINGLE_QUOTE;
        } else if (quoteStyle.equals(ANTI_QUOTE)) {
            newString = ANTI_QUOTE + checkStringQuotationMarks(text) + ANTI_QUOTE;
        } else if (quoteStyle.equals(LBRACKET) || quoteStyle.equals(RBRACKET)) {
            newString = LBRACKET + checkStringQuotationMarks(text) + RBRACKET;
        } else {
            newString = QUOTATION_MARK + checkStringQuotationMarks(text) + QUOTATION_MARK;
        }
        return widenSQLRestrict(newString, quoteStyle);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "widenSQLRestrict".
     * 
     * @param newString
     * @param quoteStyle
     * @return
     */
    private static String widenSQLRestrict(String newString, String quoteStyle) {
        String after = ""; //$NON-NLS-1$
        final String[] split = newString.split("\n"); //$NON-NLS-1$
        for (int i = 0; i < split.length; i++) {
            String string = split[i];
            if (i == 0) {
                after += getAfterString(quoteStyle, string);
            } else {
                after += getAfterString(quoteStyle, "\n" + string); //$NON-NLS-1$
            }
        }
        return after;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getAfterString".
     * 
     * @param quoteStyle
     * @param string
     * @return
     */
    private static String getAfterString(String quoteStyle, String string) {
        String after = ""; //$NON-NLS-1$
        if (string.length() > LINE_MAX_NUM) {
            String substring = string.substring(0, LINE_MAX_NUM);
            substring = substring.substring(0, getLastWord(substring, quoteStyle));
            after += substring + "\n"; //$NON-NLS-1$
            after += getAfterString(quoteStyle, string.substring(substring.length()));
        } else {
            after += string;
        }
        return after;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getLastWord".
     * 
     * @param substring
     * @param quoteStyle
     * @return
     */
    private static int getLastWord(String substring, String quoteStyle) {
        int lastIndexOf = substring.lastIndexOf(" "); //$NON-NLS-1$
        int lastIndexOf2 = substring.lastIndexOf(quoteStyle);
        if (lastIndexOf2 > 1) {
            String s = substring.substring(lastIndexOf2 - 1, lastIndexOf2);
            if (s.equals("\\")) { //$NON-NLS-1$
                lastIndexOf2 = lastIndexOf2 - 1;
            }
        }
        final int lastIndexOf3 = substring.lastIndexOf(","); //$NON-NLS-1$
        lastIndexOf = lastIndexOf < lastIndexOf2 ? lastIndexOf2 : lastIndexOf;
        lastIndexOf = lastIndexOf < lastIndexOf3 ? lastIndexOf3 : lastIndexOf;
        return lastIndexOf;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "checkStringQuotes".
     * 
     * @param str
     * @return
     */
    private static String checkStringQuotes(String str) {
        if (str == null) {
            return ""; //$NON-NLS-1$
        }
        return str.replace("'", "\\'"); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "checkStringQuotationMarks".
     * 
     * @param str
     * @return
     */
    private static String checkStringQuotationMarks(String str) {
        if (str == null) {
            return ""; //$NON-NLS-1$
        }
        return str.replace("\"", "\\\""); //$NON-NLS-1$ //$NON-NLS-2$
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addQuotesForField".
     * 
     * @param fieldName
     * @param dbType
     * @return
     */
    public static String addQuotesForField(String fieldName, String dbType) {
        if (fieldName.startsWith("\"") && fieldName.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
            return fieldName;
        }
        if (!fieldName.contains(" ")) { //$NON-NLS-1$
            return fieldName;
        }
        String newFieldName = fieldName;
        String quote = getQuoteByDBType(dbType);
        if (!newFieldName.contains(quote)) {
            newFieldName = addQuotes(newFieldName, quote, true);
        }
        return newFieldName;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "addQuotesForField".
     * 
     * @param fieldName
     * @param dbType
     * @param b
     * @return
     */
    public static String addQuotesForJETField(String fieldName, String dbType, boolean b) {
        if (fieldName == null) {
            return ""; //$NON-NLS-1$
        }
        if (fieldName.startsWith("\"") && fieldName.endsWith("\"")) { //$NON-NLS-1$ //$NON-NLS-2$
            fieldName = removeQuotes(fieldName);
        }
        String newFieldName = fieldName;
        String quote = getQuoteByDBType(dbType);
        if (!newFieldName.contains(quote)) {
            newFieldName = checkStringQuotationMarks(addQuotes(newFieldName, quote, true));
        }
        if (b) {
            return addQuotes(newFieldName, !b);
        } else {
            return newFieldName;
        }
    }

    private static boolean isLeft = true;

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getQuoteByDBType".
     * 
     * @param dbType
     * @param b
     * @return
     */
    public static String getQuoteByDBType(String dbType, boolean b) {
        isLeft = b;
        return getQuoteByDBType(dbType);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getQuoteByDBType".
     * 
     * @param dbType
     * @return
     */
    private static String getQuoteByDBType(String dbType) {
        EDatabaseType name = EDatabaseType.getTypeFromDisplayName(dbType);
        switch (name) {
        case MYSQL:
            return ANTI_QUOTE;
        case ACCESS:
            return getBracket();
        default:
            return QUOTATION_MARK;
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "getBracket".
     * 
     * @return
     */
    private static String getBracket() {
        if (isLeft) {
            isLeft = false;
            return LBRACKET;
        } else {
            isLeft = true;
            return RBRACKET;
        }
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "removeQuotesForField".
     * 
     * @param text
     * @param dbType
     * @return
     */
    public static String removeQuotesForField(String text, String dbType) {
        String newText;
        isLeft = true;
        final String quoteByDBType = getQuoteByDBType(dbType);
        if (quoteByDBType.equals(LBRACKET)) {
            if (text.length() > 2) {
                newText = text.substring(1, text.length() - 1);
                if (text.contains(RBRACKET)) {
                    newText = newText.replaceAll(RBRACKET, ""); //$NON-NLS-1$
                } else {
                    newText = text;
                }
            } else {
                newText = text;
            }

        } else {
            newText = text.replaceAll(quoteByDBType, ""); //$NON-NLS-1$
        }
        return newText;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "stringToRGB".
     * 
     * @param string
     * @return
     */
    public static RGB stringToRGB(String string) {
        RGB rgb;
        int r = 0;
        int g = 0;
        int b = 0;
        StringTokenizer token = new StringTokenizer(string, ";"); //$NON-NLS-1$
        if (token.hasMoreTokens()) {
            r = new Integer(token.nextToken());
        }
        if (token.hasMoreTokens()) {
            g = new Integer(token.nextToken());
        }
        if (token.hasMoreTokens()) {
            b = new Integer(token.nextToken());
        }
        rgb = new RGB(r, g, b);
        return rgb;
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "removeQuotes".
     * 
     * @param text
     * @return
     */
    public static String removeQuotes(String text) {
        return removeQuotes(text, QUOTATION_MARK);
    }

    /**
     * Qiang.Zhang.Adolf@gmail.com Comment method "removeQuotes".
     * 
     * @param text
     * @param quotation
     * @return
     */
    private static String removeQuotes(String text, String quotation) {
        if (text.length() > 1) {
            String substring = text.substring(0, 1);
            if (quotation.equals(substring)) {
                text = text.substring(1, text.length());
            }
            substring = text.substring(text.length() - 1, text.length());
            if (quotation.equals(substring)) {
                text = text.substring(0, text.length() - 1);
            }
        }
        return text;
    }
}
